﻿/*
============================================================================
文件名    ： CookieHelper.cs
完全限定名： M_NET.Common.CookieHelper
作者      ： 陈存腾
创建时间  ： 2012-03-19
修改时间  ： 
版本      ：
说明      ： 基础辅助类－Cookie相关
============================================================================
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace M_NET.Common
{
    /// <summary>
    /// Cookie操作辅助
    /// </summary>
    public class CookieHelper
    {
        /// <summary>
        /// 清除指定Cookie
        /// </summary>
        /// <param name="CookieName">Cookie名</param>
        public static void DelCookie(string CookieName)
        {
            try
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieName];
                if (cookie != null)
                {
                    cookie.Expires = DateTime.Now.AddYears(-3);
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 获取指定Cookie值
        /// </summary>
        /// <param name="CookieName">Cookie名</param>
        /// <returns></returns>
        public static string GetCookieValue(string CookieName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieName];
            string str = string.Empty;
            if (cookie != null)
            {
                //str = System.Text.RegularExpressions.Regex.Unescape(cookie.Value);
                str = HttpUtility.UrlDecode(cookie.Value.ToString());
            }
            return str;
        }

        /// <summary>
        /// 添加一个Cookie（24小时过期）
        /// </summary>
        /// <param name="CookieName">Cookie名</param>
        /// <param name="CookieValue">Cookie值</param>
        public static void SetCookie(string CookieName, string CookieValue)
        {
            SetCookie(CookieName, CookieValue, DateTime.Now.AddDays(1.0));
        }

        /// <summary>
        /// 添加一个Cookie
        /// </summary>
        /// <param name="CookieName">Cookie名</param>
        /// <param name="CookieValue">Cookie值</param>
        /// <param name="expires">过期时间 DateTime</param>
        public static void SetCookie(string CookieName, string CookieValue, DateTime expires)
        {
            HttpCookie cookie = new HttpCookie(CookieName)
            {
                Value = HttpUtility.UrlEncode(CookieValue),
                //Value = System.Text.RegularExpressions.Regex.Escape(CookieValue),
                Expires = expires
            };
            HttpContext.Current.Response.Cookies.Add(cookie);


        }
    }
}
